﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.Models.DataEntity;
using static bmapi.HelperClass.AssistFun;

namespace bmapi.Controllers
{
    public class CADMarkController : CADApplyController
    {
        [HttpPost, Route("cadMark/Apply")]
        public string Apply(int id)
        {
            WriteLog("cadMark/Apply", "id:"+id, true);
            //登陆者login_id
            //id实际是token 
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user != null)
            {
                //暂时取消打版工序 因为排料不能再打版中做
                user = SuitProcess(user);
                WriteDebug("cadMark/Apply-0704", "我的所有工序:code-" + user.code + ",code2-" + user.code2 + ",code3-" + user.code3);

                WriteDebug("CADMarkController", id.ToString());
                
                PC pc = null;
                if (id != 0)
                    pc = GetPC(id);
                else
                    pc = LockBed(user);

                if (pc == null)             
                    return ReturnOK(0, 0, "");//没有合适任务 
                else
                {
                    WriteDebug("CADMarkController","有流程");
                    if (id == 0)
                    {
                        if (pc.bind_id == 0)
                            AddTask(pc.step, pc.pc_id);
                        else
                            AddTask(pc.step, pc.bind_id);
                    }   
                    //检查是否有捆绑到一起的排料流程  只产生一条日志信息是因为  如果有多条的话在重新下载的时候也会有多个，
                    //可是这里实际上只有一个,还有计件工资会有错，
                    List<string> names = LockBindPC(pc,user.login_id);
                    if (names.Count == 0)
                        return ReturnOK(pc.pc_id, pc.step, pc.path);
                    else
                    {
                        if(pc.bind_id ==0)
                            return ReturnMarkOK(pc.pc_id, pc.step, pc.path, names);
                        else
                            //由于绑定的生产单只有主订单的信息是完整的   所以要把主订单传递给CAD
                            return ReturnMarkOK(pc.bind_id, pc.step, GetMainOrderName(pc.bind_id), names);
                    }                        
                }
            }
            else
            {
                return ReturnError(201, "不合法的用户");
            }
        }
        /// <summary>
        /// 根据 bindid获取主订单名
        /// </summary> 
        /// <param name="pcid"></param>
        /// <returns></returns>
        private string GetMainOrderName(int pcid)
        {
            SQLCommand sc = new SQLCommand("select name from Order_tb where id=@id","@id",pcid);
            return sc.ExecuteScalar();
        }

        [HttpGet, Route("cadMark/FindTask")]
        public string FindTask()
        {
            //当前登录者 ，用于定时刷新  
            User user = GetUserByLoginID(GetCrrentIDByToken());
            user = SuitProcess(user);
            return CheckIsHavePC(user).ToString();
        }

        [HttpGet, Route("cadMark/ReDownLoad")]  
        public string ReDownload()
        {
            try
            {
                WriteDebug("cadMark/ReDownLoad", "进入排料重新下载");
                //这个接口用来解决排料重新下载问题  
                User user = GetUserByLoginID(GetCrrentIDByToken());
                if (user == null)
                    return ReturnPCList(null);
                else
                {
                    //暂时取消打版工序 因为排料不能再打版中做 step=@ucode or step=@ucode2 or step=@ucode3
                    user = SuitProcess(user);
                    WriteDebug("cadMark/ReDownLoad", "我的所有工序:code-" + user.code + ",code2-" + user.code2 + ",code3-" + user.code3);

                    //SQLCommand sc = new SQLCommand("select PC_tb.* from PC_tb where station=@loginid and download=1 and (bind_id=0 or bind_id=pc_id)", "@loginid", user.login_id);

                    SQLCommand sc = new SQLCommand("select PC_tb.* from PC_tb join Order_tb on pc_id=id where station=@loginid and (step=@ucode or step=@ucode2 or step=@ucode3) and download=1 and (Order_tb.bind_id=0 or Order_tb.bind_id=pc_id) order by order_tb.rank desc,order_tb.finish_time asc");
                    sc.Add("@loginid", user.login_id);
                    sc.Add("@ucode", user.code);
                    sc.Add("@ucode2", user.code2);
                    sc.Add("@ucode3", user.code3);

                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return ReturnPCList(null);
                    else
                    {
                        List<PC> pc = DataTableToList<PC>(dt);
                        return ReturnPCList(pc);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteDebug("cadMark/ReDownLoad", "异常:"+ex.Message);
                throw;
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">流程id</param>
        /// <param name="process">工序编号</param>
        /// <param name="name">流程名</param>
        /// <param name="pod">pod文件名</param>
        /// <returns></returns>
        private string ReturnMarkOK(int id, int process,string currentNmae, List<string> names, int pod = 0)
        {
            WriteDebug("ReturnMarkOK", "id:" + id + "process:" + process + "cusrenName:" + currentNmae + "pod:" + pod);
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("task");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = "200";
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            p.InnerText = "OK";
            root.AppendChild(p);

            p = doc.CreateElement("id");
            p.InnerText = id.ToString();
            root.AppendChild(p);

            string sql = "select Model_tb.name from Model_tb join PC_tb on Model_tb.id=PC_tb.model_id where pc_id=@pcid";
            SQLCommand sc = new SQLCommand(sql, "@pcid", id);
            string modelName = sc.ExecuteScalar();
            if (modelName == null)
                modelName = "";
            p = doc.CreateElement("model");
            p.InnerText = modelName;
            root.AppendChild(p);

            p = doc.CreateElement("name");
            p.InnerText = currentNmae;
            root.AppendChild(p);

            p = doc.CreateElement("process");
            p.InnerText = process.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("pod");
            p.InnerText = pod.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("order");

            XmlElement mainOrder = doc.CreateElement("string");
            mainOrder.InnerText = currentNmae;
            p.AppendChild(mainOrder);

            for (int i = 0; i < names.Count; i++)
            {
                if (!names[i].Equals(currentNmae))
                {
                    XmlElement str = doc.CreateElement("string");
                    str.InnerText = names[i];
                    p.AppendChild(str);
                }                
            }
            root.AppendChild(p);
            return ConvertXmlToString(doc);
        }

        /// <summary>
        /// 判断该流程是否有绑定 且获取绑定的所有流程名
        /// </summary>
        /// <param name="pcid"></param>
        /// <returns></returns>
        private List<string> LockBindPC(PC pc,int loginid)
        {
            List<string> pcnames = new List<string>();
            if(pc.bind_id == 0)
            {
                pcnames.Add(pc.path);
                return pcnames;
            }
            //多个生产单邦定的话, 其中有一个是主生产单,其bind_id = id,其他生产单的bind_id = 主生产单的id

            WriteDebug("GetPcNames1", pc.pc_id.ToString());
            try
            {
                //改变流程工序 
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "update PC_tb set download=1,station=@loginid,maxStep=@max where bind_id=@bindid";
                pc.maxStep = GetMax(pc.maxStep, pc.step);

                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@loginid", loginid);
                sc.Add("@max", pc.maxStep);
                sc.Add("@bindid", pc.bind_id);

                int count = sc.ExecuteNonQuery();
                WriteDebug("GetPcNames2", "update=" + count.ToString());
                if (count > 0)
                {
                    sc = new SQLCommand("select path,pc_id from PC_tb where bind_id=@bindid", "@bindid", pc.bind_id);
                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return null;
                    else
                    {
                        WriteDebug("GetPcNames3", "sql=" + dt.Rows.Count);

                        foreach (DataRow item in dt.Rows)
                        {
                            pcnames.Add(item[0].ToString());
                        }
                    }
                }
                return pcnames;
            }
            catch (Exception e)
            {
                WriteDebug("GetPcNames4", e.Message);
                return null;
            }
        }
    }
}
